package com.trinea.java.common;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class TestGetNewStr {
	public static String getNewStr(String str, String regEx, StringBuffer pre) {
		Pattern p = Pattern.compile(regEx);
		Matcher m = p.matcher(str);
		int startIndex = 0;
		int endIndex = 0;
		String oldStr = "";
		String newStr = "";
		boolean b = true;
		if (m.find()) {
			oldStr = m.group(2);
			newStr = "<span style=\"color:red\">" + oldStr + "</span>";
			startIndex = m.start(2);
			endIndex = m.end(2);
			pre.append(str.substring(0, startIndex) + newStr);
			String temp = str.substring(endIndex);
			getNewStr(temp, regEx, pre);
			b = false;
		}
		if (b) {
			pre.append(str);
		}
		return pre.toString();
	}

	public static String getNewStr2(String str, String regEx, StringBuffer pre) {
		Pattern p = Pattern.compile(regEx);
		Matcher m = p.matcher(str);
		while (m.find()) {
			m.appendReplacement(pre, "$1<span style=\"color:red\">$2</span>$3");
		}
		m.appendTail(pre);
		return pre.toString();
	}

	public static void main(String[] args) {
		String str = "nbasfksdNbafspandjdk<a>dksfdkspanBajfkdadd</a><span style=\"color:red\">djksnbakdspanjksjf</span>djfkspandjdfknba";
		// String regEx = "(^|[^</])([Ss][Pp][Aa][Nn])($|[^>])";
		String regEx = "(^|[^</])([Nn][Bb][Aa])($|[^>])";
		StringBuffer pre = new StringBuffer();
		System.out.println(getNewStr(str, regEx, pre));
		StringBuffer pre2 = new StringBuffer();
		System.out.println(getNewStr2(str, regEx, pre2));
	}
}
